# KDJ策略
import talib
import module_backtest
from vnctptdType661 import *
from PyQt5 import QtCore
# CTP行情库
from vnctpmd import *
import numpy as np
import globalType
import globalvar

parlist = [['fastk_period',3,5,1],['slowk_period',15,30,1],['slowd_period',15,30,1]]

class MyStrategy(module_backtest.VirtualAccount, QtCore.QThread):
    def __init__(self, period,slippoint):
        super(MyStrategy, self).__init__(period,slippoint)
        self.period = period
        self.close = []
        self.type = 2
        self.OpenFee = 0
        self.CloseFee = 0

    def OnKline(self, mddata, arg, strategyname):
        if arg[0]<=0 or arg[1] <=0 :
            return
        # TradingDay = klinedata.TradingDay.decode()
        # klinetime = klinedata.klinetime.decode()
        self.InstrumentID = mddata.InstrumentID.decode()
        # self.exchange=mddata.exchange.decode()
        self.close.append(float(mddata.close))
        self.high.append(float(mddata.high))
        self.low.append(float(mddata.low))
        try:
            float_close = [float(x) for x in self.close]
            float_high = [float(x) for x in self.high]
            float_low= [float(x) for x in self.low]
        except Exception as e:
            pass
        #Talib中的STOCH就是KDJ指标，Talib中的SMA就是通达信中的MA,所以结果稍有区别
        #默认参数 9，3，3
        K,D = talib.STOCH(np.array(float_high),np.array(float_low),np.array(float_close),fastk_period=arg[0],
                                slowk_period=arg[1],
                                slowk_matype=0,
                                slowd_period=arg[2],
                                slowd_matype=0)
        # print('结果1:' + str(self.K))
        # print('结果2:' + str(self.D))
        # print('结果2:' + str(self.J))
        thisK =  K[len( K) - 1]
        thisD =  D[len( D) - 1]
        #thisJ =  J[len( J) - 1]
        if thisK<50 and thisD<50  and thisK > thisD  :
            #金叉
            if self.sellvol+self.sellvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Close, VN_OPT_LimitPrice,mddata.close + 1, 1)
            if self.buyvol+self.buyvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Buy, THOST_FTDC_OF_Open, VN_OPT_LimitPrice, mddata.close + 1, 1)
        elif thisK>50 and thisD>50 and thisK < thisD:
            #死叉
            if self.buyvol+self.buyvol_history > 0:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Close, VN_OPT_LimitPrice, mddata.close - 1, 1)
            if self.sellvol+self.sellvol_history < 10:
                self.InsertOrder(self.InstrumentID, '', THOST_FTDC_D_Sell, THOST_FTDC_OF_Open, VN_OPT_LimitPrice, mddata.close - 1, 1)




